import axios from 'axios'
import { ElMessage } from 'element-plus'
const baseURL = "http://localhost:8080"

const request = axios.create({
  baseURL: baseURL,
  timeout: 5000,
  withCredentials: true
},

)
//请求拦截器
request.interceptors.request.use(config => {
  // 1.发送网络请求时, 在界面的中间显示loading组件
  // 2.某一个请求发之前, 请求拦截器, 添加一个请求头(token)
      const token = localStorage.getItem('token');
      console.log(config.url);
      
      if (token && (config.url != "/user/login" && config.url!= "/user/register" )) {
        config.headers.Authorization = token;
      }
      return config;
}, err => {
   console.log(err);
})
//响应拦截器
request.interceptors.response.use(response => {
  // HTTP状态码为200且业务状态码为200时才判定为成功
  if (response.status === 200 && response.data.code === 200) {
    return response;
  }
  if(response.status === 401 || response.data.code === 401){
    localStorage.removeItem('token');
    window.location.href = "/login";
    ElMessage.error("登录过期，请重新登录");
    return Promise.reject(response.data);
  }
  // 业务状态码不为200时，显示错误信息
  ElMessage.error(response.data.message || '请求失败');
  return Promise.reject(response.data);
}, error => {
  // 处理HTTP错误
  ElMessage.error(error.message || '网络请求失败');
  return Promise.reject(error);
});


export default request;